<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"flat"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="原文地址因为很多第三方的框架基本上都运用了工厂模式，该文利用猎头来归类目标客户信息，通过联系人基本类来批量生成不同职位的对象。">
<meta property="og:type" content="article">
<meta property="og:title" content="Factory  Pattern">
<meta property="og:url" content="http://example.com/2018/12/21/Swift/Factory%20%20Pattern/index.html">
<meta property="og:site_name" content="HR&#39;s Blog">
<meta property="og:description" content="原文地址因为很多第三方的框架基本上都运用了工厂模式，该文利用猎头来归类目标客户信息，通过联系人基本类来批量生成不同职位的对象。">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="http://o95nbyrid.bkt.clouddn.com/15300945892886.png">
<meta property="article:published_time" content="2018-12-21T07:12:43.000Z">
<meta property="article:modified_time" content="2018-12-21T07:12:43.000Z">
<meta property="article:author" content="HR">
<meta property="article:tag" content="Design Patterns">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://o95nbyrid.bkt.clouddn.com/15300945892886.png">

<link rel="canonical" href="http://example.com/2018/12/21/Swift/Factory%20%20Pattern/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'en'
  };
</script>

  <title>Factory  Pattern | HR's Blog</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-61905451-1"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-61905451-1');
      }
    </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">HR's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Swimming 🏊 in the sea🌊of code!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="en">
    <link itemprop="mainEntityOfPage" href="http://example.com/2018/12/21/Swift/Factory%20%20Pattern/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="HR">
      <meta itemprop="description" content="Swimming 🏊 in the sea🌊of code!">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HR's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Factory  Pattern
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2018-12-21 15:12:43" itemprop="dateCreated datePublished" datetime="2018-12-21T15:12:43+08:00">2018-12-21</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Swift/" itemprop="url" rel="index"><span itemprop="name">Swift</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p><a target="_blank" rel="noopener" href="https://medium.com/swift-programming/design-patterns-creational-patterns-factory-pattern-in-swift-d049af54235b">原文地址</a><br>因为很多第三方的框架基本上都运用了工厂模式，该文利用猎头来归类目标客户信息，通过联系人基本类来批量生成不同职位的对象。</p>
<span id="more"></span>

<h1 id="Design-Patterns-—-Creational-Patterns-—-Factory-Pattern-in-Swift"><a href="#Design-Patterns-—-Creational-Patterns-—-Factory-Pattern-in-Swift" class="headerlink" title="Design Patterns — Creational Patterns — Factory Pattern in Swift"></a>Design Patterns — Creational Patterns — Factory Pattern in Swift</h1><p>As a budding computer scientist, you no doubt have heard of design patterns in your classes and learning paths. Design patterns are blueprints which outline the best practices that create re-usable object oriented code, solving common software problems. To avoid giving you a long history lesson, I will describe the origin of design patterns as dating back to the 1970s but gaining wide acceptance with the release of <a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Design_Patterns">Design Patterns: Elements of Reusable Object-Oriented Software</a>, published in 1994 and authored by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, collectively referred to as the **Gang of Four **(GoF). The book was wildly successful due to its description of 23 classic software design patterns. 【Design patterns are extremely useful for helping you break down complex systems into components that very often】, fit into one of the design patterns described by the <em>GoF</em>. Because I know, as developers, we love to learn and sometimes need quick references to do our jobs better, I’m dedicating time to write a series of articles, of which this is the first, to show how to use each GoF design pattern in Swift.</p>
<p>It’s common to group the design patterns we will cover into several related categories: <a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Software_design_pattern">creational patterns, structural patterns, and behavioral patterns</a>. For the remainder of this article, we are going to focus on the <em>Creational patterns</em> and cover our first pattern: the <em>Factory</em> pattern.</p>
<h4 id="Creational-Pattern-Factory-Pattern"><a href="#Creational-Pattern-Factory-Pattern" class="headerlink" title="Creational Pattern: Factory Pattern"></a>Creational Pattern: Factory Pattern</h4><p>创造型模式都是关于如何消除创建对象所涉及的复杂性的方法。 * factory *模式是封装创建对象的实现细节的一种方式，它遵循公共的基类或接口。 * factory *模式允许接收创建对象的客户端通过公共接口使用对象返回，而不关心实际创建的具体对象的类型。Creational patterns are all about ways to remove the complexities involved with creating objects. The <em>factory</em> pattern is a way to encapsulate the implementation details of creating objects, which adheres to a common base class or interface. The <em>factory</em> pattern allows the client that receives the created object to use the object return via the common interface without caring about the type of concrete object that is actually created.</p>
<p><code>工厂模式</code>将创建对象的细节从通用的接口中分开，这样允许用户正常的使用该对象。<br>The <em>factory</em> pattern separates the implementation details of creating objects from the common interface that allows users to generically use the object. Let’s consider an example to make this idea more concrete.</p>
<p>想象一下，你经营一家猎头公司，从各种工作板上获得潜在客户。对于每个工作板，你收集联系人信息和潜在对象。我只的是求职者。当你收集到联系信息，你把他们分类，并且给他们发送你为他们推荐的职位。你希望这一过程自动化，因为你每周要收集上百的联系人信息。本质上<code>电话就是金钱</code>所以你推送的越多，你就越有可能为他们推荐到合适的职位，你就越有可能得到报酬。我们将要通过<code>factory pattern</code>来解决这个问题。<br>Imagine that you run a head hunter firm that sources all of its leads from various job boards. For each job board, you collect the contact details and resumes for potential “targets”. I mean job seekers. Once you have the contact info, you categorize them and send out boilerplate emails to each contact telling the prospect about potential matches you have for them. You want to automate the process because you connect hundreds of prospects every week. You’re essentially just “dialing for dollars,” so the more prospects you can process, the greater your chances of placing a prospect into a position, and the greater likelihood you’ll get paid. We can and will solve this problem using the <em>factory</em> pattern to handle the creation of the email templates.</p>
<p>I’m going to use a Swift Playground to show one way in which we could use the <em>factory</em> pattern to achieve our goal. You can find the playground file I used for this post <a target="_blank" rel="noopener" href="https://github.com/mrkeithelliott/FactoryPattern">here</a>. To simplify things, let’s assume that each contact will have personal details along with the type of role they are seeking.</p>
<p>First, we will create the interface (or rather, protocol) that we will use to send our customized emails to our potential clients with information on the type of job they are seeking.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">protocol</span> <span class="title">JobContactProtocol</span> </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">func</span> <span class="title">sendRequestResumeEmail</span>()</span>-&gt;<span class="type">String</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Let’s also add a struct for the <em>Contact</em> object.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Contact</span></span>&#123;</span><br><span class="line">        <span class="keyword">var</span> name: <span class="type">String</span></span><br><span class="line">        <span class="keyword">var</span> email: <span class="type">String</span></span><br><span class="line">        <span class="keyword">var</span> job: <span class="type">Job</span></span><br><span class="line">        <span class="keyword">var</span> desiredSal: <span class="type">Double</span></span><br><span class="line">            </span><br><span class="line">        <span class="class"><span class="keyword">enum</span> <span class="title">Job</span> </span>&#123;</span><br><span class="line">                <span class="keyword">case</span> iOS</span><br><span class="line">                <span class="keyword">case</span> <span class="type">Android</span></span><br><span class="line">                <span class="keyword">case</span> <span class="type">Web</span></span><br><span class="line">                <span class="keyword">case</span> <span class="type">QA</span></span><br><span class="line">                <span class="keyword">case</span> <span class="type">Product_Owner</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Next, we will create several template objects that adhere to the <em>JobContacterProtocol</em>. We need templates to send to mobile developers, web developers, QA/ Testing, and product owners. We want to hide the details of these objects from clients and only expose the interface for use. What makes this pattern really useful is that each class is in charge of its implementation and can do anything as long as it adheres to the protocol. It can be used in a generic way by a client that only knows about the protocol.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">iOSDeveloperJobSeeker</span>: <span class="title">JobContactProtocol</span></span>&#123;</span><br><span class="line">        <span class="keyword">var</span> contact: <span class="type">Contact</span></span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">init</span>(<span class="params">contact</span>: <span class="type">Contact</span>)</span>&#123;</span><br><span class="line">                <span class="keyword">self</span>.contact <span class="operator">=</span> contact</span><br><span class="line">        &#125;</span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">func</span> <span class="title">sendRequestResumeEmail</span>()</span>-&gt;<span class="type">String</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;Dear <span class="subst">\(contact.name)</span>, this is the best time to be an iOS developer! Send me you&#x27;re resume today! I have job opportunities that pay <span class="subst">\(contact.desiredSal)</span>.&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">AndroidDeveloperJobSeeker</span>: <span class="title">JobContactProtocol</span></span>&#123;</span><br><span class="line">        <span class="keyword">var</span> contact: <span class="type">Contact</span></span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">init</span>(<span class="params">contact</span>: <span class="type">Contact</span>)</span>&#123;</span><br><span class="line">                <span class="keyword">self</span>.contact <span class="operator">=</span> contact</span><br><span class="line">        &#125;</span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">func</span> <span class="title">sendRequestResumeEmail</span>()</span>-&gt;<span class="type">String</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;Dear <span class="subst">\(contact.name)</span>, this is as decent time to be an Android developer! Send me you&#x27;re resume today! I have job opportunities that pay close to the <span class="subst">\(contact.desiredSal)</span> you are looking for&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">WebDeveloperJobSeeker</span>: <span class="title">JobContactProtocol</span></span>&#123;</span><br><span class="line">        <span class="keyword">var</span> contact: <span class="type">Contact</span></span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">init</span>(<span class="params">contact</span>: <span class="type">Contact</span>)</span>&#123;</span><br><span class="line">                <span class="keyword">self</span>.contact <span class="operator">=</span> contact</span><br><span class="line">        &#125;</span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">func</span> <span class="title">sendRequestResumeEmail</span>()</span>-&gt;<span class="type">String</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;Dear <span class="subst">\(contact.name)</span>, Send me you&#x27;re resume today! I have job opportunities for you.&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">QADeveloperJobSeeker</span>: <span class="title">JobContactProtocol</span></span>&#123;</span><br><span class="line">        <span class="keyword">var</span> contact: <span class="type">Contact</span></span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">init</span>(<span class="params">contact</span>: <span class="type">Contact</span>)</span>&#123;</span><br><span class="line">                <span class="keyword">self</span>.contact <span class="operator">=</span> contact</span><br><span class="line">        &#125;</span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">func</span> <span class="title">sendRequestResumeEmail</span>()</span>-&gt;<span class="type">String</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;Dear <span class="subst">\(contact.name)</span>, The market is tough but the code is still buggy!  Good news for you because I know the best companies for buggy code and they need you!&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">ProductOwnerDeveloperJobSeeker</span>: <span class="title">JobContactProtocol</span></span>&#123;</span><br><span class="line">        <span class="keyword">var</span> contact: <span class="type">Contact</span></span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">init</span>(<span class="params">contact</span>: <span class="type">Contact</span>)</span>&#123;</span><br><span class="line">                <span class="keyword">self</span>.contact <span class="operator">=</span> contact</span><br><span class="line">        &#125;</span><br><span class="line">            </span><br><span class="line">        <span class="function"><span class="keyword">func</span> <span class="title">sendRequestResumeEmail</span>()</span>-&gt;<span class="type">String</span>&#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="string">&quot;Dear <span class="subst">\(contact.name)</span>, Times are still good to be in development.  Maybe you should consider learning to code or going back to code. If we can cut your desired salary of <span class="subst">\(contact.desiredSal)</span> in half, I should be able to place you as a contract to hire. Send me your resume!&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Our next step is to create the actual factory that our client will use to get a concrete object that adheres to our protocol. The factory object in our case has just one method to return the job seeker object that adheres to the <em>JobContacterProtocol</em> based on a <em>contact</em> object that is passed in as a parameter to the function.</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">JobContacterFactory</span></span>&#123;</span><br><span class="line">        <span class="keyword">static</span> <span class="function"><span class="keyword">func</span> <span class="title">getJobSeeker</span>(<span class="params">contact</span>: <span class="type">Contact</span>)</span>-&gt;<span class="type">JobContactProtocol</span> &#123;</span><br><span class="line">                <span class="keyword">switch</span> contact.job &#123;</span><br><span class="line">                <span class="keyword">case</span> .iOS:</span><br><span class="line">                        <span class="keyword">return</span> iOSDeveloperJobSeeker(contact: contact)</span><br><span class="line">                <span class="keyword">case</span> .<span class="type">Android</span>:</span><br><span class="line">                        <span class="keyword">return</span> <span class="type">AndroidDeveloperJobSeeker</span>(contact: contact)</span><br><span class="line">                <span class="keyword">case</span> .<span class="type">Web</span>:</span><br><span class="line">                        <span class="keyword">return</span> <span class="type">WebDeveloperJobSeeker</span>(contact: contact)</span><br><span class="line">                <span class="keyword">case</span> .<span class="type">QA</span>:</span><br><span class="line">                        <span class="keyword">return</span> <span class="type">QADeveloperJobSeeker</span>(contact: contact)</span><br><span class="line">                <span class="keyword">case</span> .<span class="type">Product_Owner</span>:</span><br><span class="line">                        <span class="keyword">return</span> <span class="type">ProductOwnerDeveloperJobSeeker</span>(contact: contact)</span><br><span class="line">                &#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Our factory hides the need to know the type of object created because we will use our interface methods when we want to do anything with the created object. The added benefit of doing this is that we can add, change, or remove concrete objects from our factory without changing our client code!</p>
<p>In our example, we can create several contacts that we want to reach out to with opportunities. We can then contact these prospects with our exposed interface and cutdown our processing time with automation!</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> contacts <span class="operator">=</span> [<span class="type">Contact</span>]()</span><br><span class="line">contacts.append(<span class="type">Contact</span>(name: <span class="string">&quot;J Rob&quot;</span>, email: <span class="string">&quot;jrob@example.com&quot;</span>, job: .iOS, desiredSal: <span class="number">135000</span>))</span><br><span class="line">contacts.append(<span class="type">Contact</span>(name: <span class="string">&quot;K Rock&quot;</span>, email: <span class="string">&quot;krock@example.com&quot;</span>, job: .<span class="type">Android</span>, desiredSal: <span class="number">134000</span>))</span><br><span class="line">contacts.append(<span class="type">Contact</span>(name: <span class="string">&quot;P Money&quot;</span>, email: <span class="string">&quot;pmoney@example.com&quot;</span>, job: .<span class="type">Web</span>, desiredSal: <span class="number">110000</span>))</span><br><span class="line">contacts.append(<span class="type">Contact</span>(name: <span class="string">&quot;S Sham&quot;</span>, email: <span class="string">&quot;ssham@example.com&quot;</span>, job: .<span class="type">QA</span>, desiredSal: <span class="number">95000</span>))</span><br><span class="line">contacts.append(<span class="type">Contact</span>(name: <span class="string">&quot;L Roger&quot;</span>, email: <span class="string">&quot;lroger@example.com&quot;</span>, job: .<span class="type">Product_Owner</span>, desiredSal: <span class="number">165000</span>))</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> contact <span class="keyword">in</span> contacts&#123;</span><br><span class="line">    <span class="keyword">let</span> client <span class="operator">=</span> <span class="type">JobContacterFactory</span>.getJobSeeker(contact: contact)</span><br><span class="line">    print (client.sendRequestResumeEmail())</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src="http://o95nbyrid.bkt.clouddn.com/15300945892886.png"></p>
<p>That’s it! Our factory example is complete. We can now send customized emails to our contacts based on the type of job they are seeking. We could expand on our example as our needs change and not have to change code that our client uses as long as our interface doesn’t change. That means we could add new jobs and job seeker objects to send customized emails to new contact types with no change to the client that uses our <em>JobContactProtocol</em>. We could also change the logic for creating our template, since that would only encompass an implementation change.</p>
<h4 id="Wrapping-Up"><a href="#Wrapping-Up" class="headerlink" title="Wrapping Up"></a>Wrapping Up</h4><p>The <em>factory</em> pattern makes it possible for us to hide the implementation details for creating objects by allowing our clients to rely solely on a common interface for interacting with our objects. This allows us to remove unnecessary complexities involved with creating objects that have similar behavioral needs. The <em>factory</em> pattern also promotes separation and abstraction which both lead to reusable code that is easier to maintain. You can find the playground file for this article <a target="_blank" rel="noopener" href="https://github.com/mrkeithelliott/FactoryPattern">here</a>.</p>
<p>On a lighter note, I also wrote an article on why creating native apps is probably the best way to go in most of your mobile development endeavors. Read it and weigh in the discussion!</p>

    </div>

    
    
    
        

  <div class="followme">
    <p>Welcome to my other publishing channels</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Design-Patterns/" rel="tag"># Design Patterns</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2018/12/21/Swift/JSON/" rel="prev" title="JSON">
      <i class="fa fa-chevron-left"></i> JSON
    </a></div>
      <div class="post-nav-item">
    <a href="/2018/12/21/Swift/Defer/" rel="next" title="Defer">
      Defer <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Design-Patterns-%E2%80%94-Creational-Patterns-%E2%80%94-Factory-Pattern-in-Swift"><span class="nav-number">1.</span> <span class="nav-text">Design Patterns — Creational Patterns — Factory Pattern in Swift</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Creational-Pattern-Factory-Pattern"><span class="nav-number">1.0.0.1.</span> <span class="nav-text">Creational Pattern: Factory Pattern</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Wrapping-Up"><span class="nav-number">1.0.0.2.</span> <span class="nav-text">Wrapping Up</span></a></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">HR</p>
  <div class="site-description" itemprop="description">Swimming 🏊 in the sea🌊of code!</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:caohr@outlook.com" title="E-Mail → mailto:caohr@outlook.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">HR</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
